package cn.micai.base.io;

import java.io.*;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/23 10:48
 * @Description: Java内置的实现序列化、反序列化
 */
public class JavaSerializeDeserializeMain {

    /**
     * Java内置的实现序列化
     * @param employee
     * @return
     * @throws IOException
     */
    public static byte[] serialize(Employee employee){
        // 定义一个字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = null;
        // 对象输出流
        ObjectOutputStream objectOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            // 将对象写入到字节数组输出，进行序列化
            objectOutputStream.writeObject(employee);
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                objectOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Java内置的实现反序列化
     * @param employeeArray
     * @return
     */
    public static Employee deserialize(byte[] employeeArray) {
        // 定义字节数组输入流
        ByteArrayInputStream byteArrayInputStream = null;
        // 执行反序列化，从流中读取对象
        ObjectInputStream objectInputStream = null;
        try {
            byteArrayInputStream = new ByteArrayInputStream(employeeArray);
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return (Employee) objectInputStream.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                objectInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String [] args) {

        Employee employee = new Employee();
        employee.setEmployeeId(1);
        employee.setEmployeeName("赵新国");
        employee.setDepartment("软件工程师");
        // 序列化
        byte[] serialize = serialize(employee);
        System.out.println(serialize);
        // 反序列化
        Employee deserialize = deserialize(serialize);
        System.out.println(deserialize.toString());

    }

}
